package ch.fusun.baron.turn;

import java.util.HashMap;
import java.util.Map;

import ch.fusun.baron.core.rmi.User;
import ch.fusun.baron.data.AbstractDataProvider;
import ch.fusun.baron.data.DataListener;
import ch.fusun.baron.data.DataUpdate;

/**
 * The user turn service implementation
 */
public class UserTurnServiceImpl extends AbstractDataProvider implements
		UserTurnService {

	private final Map<User, Integer> userTurnPoints = new HashMap<User, Integer>();

	@Override
	public void increaseTurnPoints(User user, int points) {
		Integer original = userTurnPoints.get(user);
		if (original == null) {
			original = 0;
		}
		setPoints(user, original + points);
	}

	@Override
	public DataUpdate createFullUpdate() {
		return new UserTurnDataUpdate(userTurnPoints);
	}

	@Override
	public void setPoints(User user, int points) {
		userTurnPoints.put(user, points);
		for (DataListener listener : getListeners()) {
			listener.dataChanged(new SetPointsDataUpdate(user, points));
		}
	}

	@Override
	public int getTurnPoints(User user) {
		Integer integer = userTurnPoints.get(user);
		if (integer == null) {
			return 0;
		}
		return integer;
	}

	@Override
	public void decreaseTurnPoints(User user, int turnCost) {
		increaseTurnPoints(user, -turnCost);
	}

}
